package com.seashop.config;

import com.seashop.constant.MQConstant;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author moredln
 * @desc RabbitMQ配置
 * @date 2020/12/3 12:07 上午
 */
@Configuration
public class RabbitMQConfig {

    @Bean
    public RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        return rabbitTemplate;
    }

    /**
     * Direct交换机
     *
     * @return
     */
    @Bean
    public DirectExchange directExchange() {
        return new DirectExchange(MQConstant.SEASHOP_DIRECT_EXCHANGE);
    }

    /**
     * 发送短信队列
     * durable=true 是否持久
     *
     * @return
     */
    @Bean
    public Queue messageSendQueue() {
        return new Queue(MQConstant.MQ_QUEUE_USER_MESSAGE_SEND, true);
    }

    /**
     * 绑定  将队列和交换机绑定, 并设置用于匹配键：MQConstant.MQ_QUEUE_USER_MESSAGE_SEND
     *
     * @return
     */
    public Binding bindingMessageSendDirect() {
        return BindingBuilder.bind(messageSendQueue()).to(directExchange()).with(MQConstant.MQ_QUEUE_USER_MESSAGE_SEND);
    }

}
